import {Upload, Button, Icon, Modal} from 'antd';
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import classnames from 'classnames'
import ImageService from './imageService'
import qs from 'qs'
import urlencode from 'urlencode'

export default class LwjUpload extends Component {

  state = {
    fileList: []
  };

  componentDidMount() {

    // 元处理方式
    if (this.props.fileLists) {
      let picUrlsAAA = this.props.fileLists;
      const getUrlAAA = (picUrls) => {
        let promiseArr = [];
        const IMAGE_THUMBNAIL_PARAM_ALIOSS = '?x-oss-process=image/resize,m_lfit,h_400,w_400';
        if (picUrls && picUrls.split(';').length > 0) {
          let newpicUrls = picUrls.split(';');
          if (newpicUrls[newpicUrls.length - 1] == "") {
            newpicUrls.pop();
          }
          newpicUrls.map(img => {
            promiseArr.push(new Promise(function (resolve, reject) {
              ImageService.show(img, (imgUrl) => {
                let thumbnail = '';
                if (imgUrl) {
                  thumbnail = imgUrl.split('?')[0] + IMAGE_THUMBNAIL_PARAM_ALIOSS;
                }
                resolve({url: imgUrl, thumbnail: thumbnail, orginUrl: img});
              });
            }));
          });
          return promiseArr;
        }
      }
      const dealedTargetUrlAAA = getUrlAAA(picUrlsAAA);
      let sureDealedUrlAAA = [];
      dealedTargetUrlAAA.forEach((value, index) => {
        value.then((val) => {
          // let newName = val   .orginUrl   .split('/')[     val       .orginUrl
          // .split('/')       .length - 1   ];
          const name = urlencode.decode(qs.parse(val.url)['response-content-disposition'], 'utf-8')
          const tname = name.slice(name.indexOf("filename*=UTF-8") + 17)
          sureDealedUrlAAA.push({
            name: tname.length > 30
              ? tname.slice(-30)
              : tname,
            uid: index,
            url: val.url,
            response: {
              result: val.orginUrl
            }
          });
          this.setState({fileList: sureDealedUrlAAA});
        })
      })
    }

    // 会有时效问题 if (this.props.fileLists) {   let dealedTargetUrlAAA =
    // this.props.fileLists;   let sureDealedUrlAAA = [];   dealedTargetUrlAAA
    // .split(';')     .forEach((value, index) => {       const name =
    // urlencode.decode(qs.parse(value)['response-content-disposition'], 'utf-8')
    // const tname = name.slice(name.indexOf("filename*=UTF-8") + 17)
    // sureDealedUrlAAA.push({         name: tname,         uid: index,         url:
    // value,         response: {           result: value         }       })
    // this.setState({fileList: sureDealedUrlAAA});     }) }

  }

  render() {
    const {
      uploadTitle,
      uploadIcon = "",
      btnType = "ghost",
      target,
      fileType,
      fileSize = 99999,
      showUploadList = true,
      onChange,
      accept,
      maxfile
      // imgWidth, imgHeight
    } = this.props;

    const {fileList} = this.state;

    let _self = this;
    let proper = {
      action: target,
      showUploadList,
      accept,
      multiple: maxfile > 1,
      beforeUpload(file) {
        let flag = true;
        // 尺寸监测暂时取消 if (imgWidth && imgHeight) {     flag = testInch(file); }
        if (fileType) {
          const isJPG = file.type === fileType;
          if (!isJPG) {
            Modal.info({content: `只能上传 ${fileType} 格式的文件哦！`});
            flag = false;
          }
        }
        return flag;
      },
      fileList
    }

    const preChange = ({file, fileList, event}) => {

      this.setState({fileList});

      // 限制尺寸
      const isLt2M = file.size / 1024 / 1024 < fileSize;
      if (file.size && !isLt2M) {
        fileList.forEach((val, index) => {
          if (val.uid == file.uid) {
            fileList.splice(index, 1);
          }
        })
        this.setState({fileList});
        Modal.error({content: `只能上传小于 ${fileSize} M的文件哦！`});
      }
      // 获取下载链接
      if (file.response) {
        let picUrlsAAA = file.response.result;
        const getUrlAAA = (picUrls) => {
          let promiseArr = [];
          const IMAGE_THUMBNAIL_PARAM_ALIOSS = '?x-oss-process=image/resize,m_lfit,h_400,w_400';
          if (picUrls && picUrls.split(';').length > 0) {
            picUrls
              .split(';')
              .map(img => {
                promiseArr.push(new Promise(function (resolve, reject) {
                  ImageService.show(img, (imgUrl) => {
                    let thumbnail = ''
                    if (imgUrl) {
                      thumbnail = imgUrl.split('?')[0] + IMAGE_THUMBNAIL_PARAM_ALIOSS;
                    }
                    resolve({url: imgUrl, thumbnail: thumbnail});
                  });
                }));
              });
            return promiseArr;
          }
        }

        const dealedTargetUrlAAA = getUrlAAA(picUrlsAAA);
        let sureDealedUrlAAA = [];
        dealedTargetUrlAAA.forEach((value, index) => {
          value.then((val) => {
            sureDealedUrlAAA.push({
              name: index,
              uid: file.uid,
              url: val.url,
              response: {
                result: val.url
              }
            })
            fileList.forEach((val) => {
              if (val.uid == sureDealedUrlAAA[0].uid) {
                val.url = sureDealedUrlAAA[0].url;
              }
            })
            this.setState({fileList});
            // 与处理数据
            let targetValue = '';
            for (let i = 0; i < fileList.length; i++) {
              if (fileList[i].response) {
                targetValue += fileList[i].response.result + ';';
              }
            }
            targetValue = targetValue.substring(0, targetValue.length - 1);
            if (targetValue == '') {
              onChange('')
            }
            if (targetValue) {
              onChange(targetValue)
            }
          })
        })
      }

    }
    // const testInch = (file) => {     let reader = new FileReader();     const
    // tHeight = imgHeight;     const tWidrh = imgWidth;     reader.onload =
    // function (theFile) {         let image = new Image();         image.onload =
    // function () {             let width = this.width;             let height =
    // this.height;             if (width !== tWidrh || height !== tHeight) {
    // Modal.info({content: `上传图片尺寸要求为${tWidrh}*${tHeight},请重新选择！`}) return false; }
    // else {                 return true;        }    } image.src =
    // theFile.target.result;     } reader.readAsDataURL(file); }
    const uploadButton = (
      <Button type={btnType}>
        <Icon type={uploadIcon}/> {uploadTitle}
      </Button>
    )
    return (
      <Upload {...proper} onChange={preChange}>
        {fileList.length >= maxfile
          ? null
          : uploadButton}
      </Upload>
    );
  }
}

LwjUpload.props = {
  uploadTitle: PropTypes.string,
  uploadIcon: PropTypes.string,
  btnType: PropTypes.string,
  target: PropTypes.string.isRequired,
  name: PropTypes.string,
  fileType: PropTypes.string,
  fileSize: PropTypes.number,
  onChange: PropTypes.func,
  showUploadList: PropTypes.bool
}
